package com.winit.cloudlink.message.monitor;

import com.alibaba.fastjson.JSON;
import com.winit.cloudlink.common.URL;
import com.winit.cloudlink.common.utils.HttpUtils;
import com.winit.cloudlink.common.utils.NetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class UpushAlerter implements Alerter {
	private static final Logger logger = LoggerFactory.getLogger(UpushAlerter.class);

	public static final String UPUSH_SEND_API_URL = "http://upush2.winit.com.cn/api/v1/sends";
	public static final String UPUSH_TOPIC = "CLOUDLINK_SEND_MESSAGE_ERROR";
	public static final String UPUSH_GROUP = "CLOUDLINK_SEND_MESSAGE_ERROR";

	private String upushSendApiUrl = UPUSH_SEND_API_URL;

	public UpushAlerter() {

	}

	public UpushAlerter(URL upushUrl) {
		this.upushSendApiUrl = upushUrl.toFullString();
	}

	@Override
	public void alert(String message) {
		try {
			CloudlinkSendMessageErrorModel model = new CloudlinkSendMessageErrorModel(NetUtils.getLocalHost(), message);
			UpushSendParameter parameter = new UpushSendParameter(UPUSH_GROUP, UPUSH_TOPIC, model);
			HttpUtils.jsonPost(upushSendApiUrl, JSON.toJSONString(parameter));
		} catch (IOException e) {
			logger.error("发告警失败.", e);
		} finally {

		}
	}


	public static class CloudlinkSendMessageErrorModel {
		private String ip;
		private String message;

		public CloudlinkSendMessageErrorModel() {
		}

		public CloudlinkSendMessageErrorModel(String ip, String message) {
			this.ip = ip;
			this.message = message;
		}

		public String getIp() {
			return ip;
		}

		public void setIp(String ip) {
			this.ip = ip;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}
	}

	public static class UpushSendParameter {
		public String group;
		public String topic;
		public String dataModel;

		public UpushSendParameter() {
		}

		public UpushSendParameter(String group, String topic, Object dataModel) {
			this.group = group;
			this.topic = topic;
			this.dataModel = JSON.toJSONString(dataModel);
		}
	}
}
